/*
 * @Date: 2020-08-24 14:47:55
 * @LastEditors: xujianxing
 * @LastEditTime: 2020-08-24 15:31:51
 * @FilePath: \nili\src\common\filters\http-exception.filter.ts
 * Http 异常过滤器
 */

import {
  ExceptionFilter,
  ArgumentsHost,
  HttpException,
  Catch,
} from '@nestjs/common';
import { Response, Request } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    const { message } = exception;
    response.status(status).json({
      code: status,
      message,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}
